package com.ejlchina.tool.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.findNavController
import androidx.viewpager2.widget.ViewPager2
import com.adolf.androiddemo.R
import com.adolf.androiddemo.databinding.FragmentConfigBinding
import com.ejlchina.tool.MainActivity
import com.ejlchina.tool.adapter.pageadapter.ConfigFragmentOfflinePagerAdapter
import com.ejlchina.tool.adapter.pageadapter.ConfigFragmentPagerAdapter
import com.ejlchina.tool.base.BaseBindingFragment2
import com.ejlchina.tool.constant.DEVICE_MODE_ONLINE
import com.ejlchina.tool.extension.safeNavigate
import com.ejlchina.tool.fragment.offline.ConfigOfflineViewPagerFragment
import com.ejlchina.tool.fragment.viewpager.ConfigViewPagerFragment
import com.ejlchina.tool.singleton.GlobalConnectObject
import com.ejlchina.tool.util.LOG_TAG
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.huyuhui.fastble.data.BleDevice
import kotlinx.coroutines.launch


class ConfigFragment : BaseBindingFragment2<FragmentConfigBinding>() {
    private val fragmentList = mutableListOf<ConfigViewPagerFragment>()
    private var pageAdapter :ConfigFragmentPagerAdapter? = null

    private val fragmentListOffline = mutableListOf<ConfigOfflineViewPagerFragment>()
    private var pageAdapterOffline : ConfigFragmentOfflinePagerAdapter? = null
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
        initData()
    }

    private fun initViews(){
        Log.i(LOG_TAG,"Config fragment onViewCreated")
        setHeadVisibility(View.GONE)
//        setFirstComeLogic()
        initListeners()
        setHeadText()
    }

    private fun setHeadText(){
        binding.includeHead.tvAppTitle.text =
            if (checkDeviceMode() == DEVICE_MODE_ONLINE) getString(R.string.device_nickname_online) else getString(R.string.device_nickname_offline)
    }

    private fun initData(){
        if (checkDeviceMode() == DEVICE_MODE_ONLINE){
            initTabAndViewPager()
        } else {
            initTabAndViewPagerOffline()
        }
        (requireActivity() as MainActivity).clearAllSaveData(1)
    }

    private fun initListeners(){
        binding.includeHead.ivMenu.setOnClickListener {
            (requireActivity() as MainActivity).openDraw()
        }

        binding.includeHead.tvConnectCount.setOnClickListener {
            if (checkDeviceMode() == DEVICE_MODE_ONLINE){
                findNavController().safeNavigate(R.id.action_config_to_scan)
            } else {
                findNavController().safeNavigate(R.id.action_config_to_scan_offline)
            }

        }
    }

    private fun initTabAndViewPager(){
        GlobalConnectObject.getCurrentConnectDeviceList().sortBy { it.bucketNo }
        binding.tabLayout.removeAllTabs()
        Log.i(LOG_TAG,"Fragment Page Size---${GlobalConnectObject.getCurrentConnectDeviceList().size}")
        binding.tabLayout.tabMode = TabLayout.MODE_SCROLLABLE
        fragmentList.clear()
        fragmentList.addAll(GlobalConnectObject.getCurrentConnectDeviceList().map { ConfigViewPagerFragment(it) })
        binding.viewPager.offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
        pageAdapter = ConfigFragmentPagerAdapter(this,fragmentList)
        binding.viewPager.adapter = pageAdapter

        TabLayoutMediator(
            binding.tabLayout, binding.viewPager
        ) { tab, position -> tab.setText("${GlobalConnectObject.getCurrentConnectDeviceList()[position].bucketNo}#") }.attach()
    }

    private fun initTabAndViewPagerOffline(){
        binding.tabLayout.tabMode = TabLayout.MODE_SCROLLABLE
        fragmentListOffline.clear()
        fragmentListOffline.addAll(GlobalConnectObject.getCurrentConnectDeviceList().map { ConfigOfflineViewPagerFragment(it) })
        binding.viewPager.offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
        Log.i(LOG_TAG,"Fragment Page Size---${fragmentList.size}")
        pageAdapterOffline = ConfigFragmentOfflinePagerAdapter(this,fragmentListOffline)
        binding.viewPager.adapter = pageAdapterOffline
        TabLayoutMediator(
            binding.tabLayout, binding.viewPager
        ) { tab, position -> tab.setText("${position + 1}#") }.attach()
    }

    private fun setConnectCount(){
        if (isAdded){
            val count = viewModelActivity.getAllConnectDevices().size
            binding.includeHead.tvConnectCount.text = "$count"
        }
    }

    override fun whenDeviceDisConnect(disConnectDevice: BleDevice) {
        super.whenDeviceDisConnect(disConnectDevice)
        dismissLoading()
        if (isAdded){
            setConnectCount()
            if (viewModelActivity.getAllConnectDevicesCount() > 0){
                if (checkDeviceMode() == DEVICE_MODE_ONLINE){
                    initTabAndViewPager()
                } else {
                    initTabAndViewPagerOffline()
                }
            }
        }
    }
    override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup): FragmentConfigBinding {
        return FragmentConfigBinding.inflate(inflater,container,true)
    }

    override fun initOnCreateView() {
        super.initOnCreateView()
        setActionBarPadding(false)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        (requireActivity() as MainActivity).restoreData(1)
        Log.i(LOG_TAG,"Config fragment onDestroy View")
    }

    override fun onResume() {
        super.onResume()
        setConnectCount()
    }

}
